// #include "uart_task.h"

#include "uart.h"
#include "myboard.h"

#include "cbb_ph_mb_slave.h"
#include "cbb_verify_crc16.h"
#include "cbb_init.h"

#include "FreeRTOS.h"
#include "task.h"

static PH_t* pstMBSlave;

static uint16_t u16HoldingRegs[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
static uint16_t u16InputRegs[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
static uint8_t u8RxData[128];
static uint8_t u8TxData[128];

static uint8_t uart_modbus_task(uint32_t u32RxLen){

    // 解析数据
    PH_Buf_t stRxBuffer = {
        .pu8Buffer = u8RxData,
        .u32BufferLen = sizeof(u8RxData),
        .u32DataLen = u32RxLen,
    };
    uint8_t u8Ret = cbb_mb_slave_parse(pstMBSlave, &stRxBuffer);

    // 解析失败，跳过
    if(u8Ret != PH_OK) return 1;
    
    // 构建数据
    PH_Buf_t stTxBuffer = {
        .pu8Buffer = u8TxData,
        .u32BufferLen = sizeof(u8TxData),
        .u32DataLen = 0,
    };
    u8Ret = cbb_mb_slave_build(pstMBSlave, &stTxBuffer);
    
    // 构建失败，跳过
    if(u8Ret != PH_OK) return 1;

    // 发送数据
    return uart_transmit(pstUsart1, stTxBuffer.pu8Buffer, stTxBuffer.u32DataLen);
}

void uart_task_run(void* pvArgs)
{
    (void) pvArgs;
    while(1){
        // 串口监控
        uart_monitor(pstUsart1);

        // 判断串口是否接收完成
        if(!get_device_event(pstUsart1, UART_DATA_READY)) goto res;

        // 清除事件标志
        clear_device_event(pstUsart1, UART_DATA_READY);
        
        // 获取接收数据长度
        uint32_t u32RxLen = uart_receive(pstUsart1, u8RxData);

        // 数据长度为0，跳过
        if(u32RxLen == 0) goto res;

        // 处理modbus
        if(0 == uart_modbus_task(u32RxLen)) goto res;

        // 任务延时跳转
        res:
            vTaskDelay(pdMS_TO_TICKS(20));
    }
}

void uart_task_init(void){

    static StaticTask_t stUartTaskTCB;
    static StackType_t  UartTaskStack[configMINIMAL_STACK_SIZE];
    static TaskHandle_t pstUartTaskHandle = NULL;
    (void) pstUartTaskHandle;

    pstUartTaskHandle = xTaskCreateStatic(
        uart_task_run,                   /* 任务函数 */
        "UartTask",                          /* 名字 */
        configMINIMAL_STACK_SIZE,      /* 栈深度（字） */
        NULL,                           /* 参数 */
        tskIDLE_PRIORITY + 2,               /* 优先级 */
        UartTaskStack,                   /* 静态栈数组 */
        &stUartTaskTCB);                 /* 静态 TCB 变量 */

    PH_MB_Slave_t stMBSlave = {
        .pu16HoldingRegs = u16HoldingRegs,
        .pu16InputRegs = u16InputRegs,
        .u16HoldingRegsSize = sizeof(u16HoldingRegs),
        .u16InputRegsSize = sizeof(u16InputRegs),
        .u8Addr = 1,
    };

    pstMBSlave = cbb_mb_slave_register(&stMBSlave, 
        cbb_verify_crc16_check, cbb_verify_crc16_append);
}
INIT_PORT_TASK(uart_task_init);
